<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
	<title></title>
	<link rel="stylesheet" type="text/css" href="<?php echo PATH?>/web/css/ui.jqgrid.css">
	<link rel="stylesheet" type="text/css" href="<?php echo PATH?>/web/css/pepper-grinder/jquery-ui-1.10.3.custom.css">
	<link rel="stylesheet" type="text/css" href="<?php echo PATH?>/web/css/styles.css"/>
	
	<script type="text/javascript" src="<?php echo PATH?>/web/js/jquery-1.10.2.js"></script>
	<script type="text/javascript" src="<?php echo PATH?>/web/js/jquery-ui-1.10.3.custom.js"></script>
	<script type="text/javascript" src="<?php echo PATH?>/web/js/jqgrid/jquery.jqGrid.min.js"></script>
	<script type="text/javascript" src="<?php echo PATH?>/web/js/jqgrid/grid.locale-es.js"></script>
</head>
<body>
	<script>
	
	function mensaje(response, postdata) {	
    	//parseo la respuesta del servidor
    	var result = null;
    	//parseo la respuesta del servidor
    	if(response!=null && response.responseText!="\r\n"){
    		result = jQuery.parseJSON( response.responseText );
    		if(result.estado!="OK"){
    			mostrarMsj("Cliente","ERROR",result.errores);
    		}else{
    			mostrarMsj("Cliente","INFO",result.info);
    		}	
    	}else{
    		mostrarMsj("Cliente","INFO","La operación se ha realizado correctamente");
    	}
        var errors = "";

        var new_id = null;

        return [response.success, errors, new_id];
   	}
	    
	function mostrarMsj(selector,tipoMsj,msj){
		$("#msj"+tipoMsj+selector+" span").html("<b>"+tipoMsj+"</b>:"+msj);
		$("#msj"+tipoMsj+selector+".message").fadeIn("slow");
    }
	
	function mensajeError(data){
		return '<span class="ui-icon ui-icon-alert" style="float: left; margin-right: .3em;"></span>'+
			"<strong>ERROR :<strong></br> La operación no se ha podido realizar";
			//Status: '" + data.statusText + "'. Error code: " + data.status 
	}
	
	
		    
	function calcularPos(postdata){
		var respuesta ="";
	    postdata.latitud = "";
	    postdata.longitud = "";
	    postdata.direccion = "";
	    var calle = str_replace (' ', '+', postdata.calle);
	    var localidad = str_replace (' ', '+', postdata.localidad);
	    var provincia = str_replace (' ', '+', postdata.provincia);
	   	var direccion = calle + ',' + localidad + ',' + provincia + ',Argentina'
	    $.ajax({
		    url: "http://maps.googleapis.com/maps/api/geocode/json?address="+ direccion +"&sensor=false",
		    async:false
		}).done(function( response ){
		    	respuesta = response;
		  	});
		if(respuesta.status == "OK"){
			postdata.direccion =  postdata.calle + ',' + postdata.localidad + ',' + postdata.provincia + ',Argentina'  	
			postdata.latitud = respuesta.results[0].geometry.location.lat;
			postdata.longitud = respuesta.results[0].geometry.location.lng;
		} 
	}
	
	function str_replace (search, replace, subject, count) {
  
  var i = 0,
    j = 0,
    temp = '',
    repl = '',
    sl = 0,
    fl = 0,
    f = [].concat(search),
    r = [].concat(replace),
    s = subject,
    ra = Object.prototype.toString.call(r) === '[object Array]',
    sa = Object.prototype.toString.call(s) === '[object Array]';
  s = [].concat(s);
  if (count) {
    this.window[count] = 0;
  }

  for (i = 0, sl = s.length; i < sl; i++) {
    if (s[i] === '') {
      continue;
    }
    for (j = 0, fl = f.length; j < fl; j++) {
      temp = s[i] + '';
      repl = ra ? (r[j] !== undefined ? r[j] : '') : r[0];
      s[i] = (temp).split(f[j]).join(repl);
      if (count && s[i] !== temp) {
        this.window[count] += (temp.length - s[i].length) / f[j].length;
      }
    }
  }
  return sa ? s : s[0];
}

	
	jQuery(document).ready(function () {
		jQuery("#dataTable").jqGrid({
	   	url:'../cliente/listarJson',
		datatype: "json",
	   	colNames:[
			'idCliente',
			'Nombre y apellido',
			'Tipo ID',
			'Identificación',
			'Código',
			'Depto.',
			'Dirección',
			'Calle',
			'Localidad',
			'Provincia'
		],
		colModel :[
            {
            	name:'idCliente',
            	index:'idCliente',
            	hidden:true
            },
            {
            	name:'nombreApell',
            	index:'nombreApell',
            	width:'100',
            	align:'center',
            	editrules:{required:true},
            	editoptions: {maxlength: 40},
            	editable:true
            },
            {
        		name:'tipoIdentif',
        		index:'tipoIdentif',
        		width:'40',
        		align:'center',
        	//	formatter:cuentaBGBA,
        		editable:true,
        		edittype:"select",
        		editoptions: { value: '1:DNI; 2:CUIT' } ,
        		editrules:{required:true},
        		searchoptions: { sopt: ['eq','cn'] }
        	},
            {
            	name:'identificacion',
            	index:'identificacion',
            	width:'80',
            	align:'center',
            	editrules:{required:true},
            	editoptions: {maxlength: 15},
            	editable:true
            },
            {
            	name:'codCliente',
            	index:'codCliente',
            	width:'80',
            	align:'center',
            	editrules:{required:true},
            	editoptions: {maxlength: 50},
            	editable:true
            },
             {
            	name:'departamento',
            	index:'departamento',
            	width:'40',
            	align:'center',
            //	editrules:{required:true},
            	editoptions: {maxlength: 5},
            	editable:true
            },
            {
            	name:'direccion',
            	index:'direccion',
            	width:'150',
            	align:'center',
            //	editrules:{required:true},
            //	editoptions: {maxlength: 100},
            	editable:false
            },
            {
            	name:'calle',
            	index:'calle',
            	width:'150',
            	align:'center',
            	editrules:{required:true,edithidden:true},
            	editoptions: {maxlength: 100},
            	editable:true,
            	hidden:true
            },
            {
            	name:'localidad',
            	index:'localidad',
            	width:'150',
            	align:'center',
            	editrules:{required:true,edithidden:true},
            	editoptions: {maxlength: 50},
            	editable:true,
            	hidden:true
            },
            {
            	name:'provincia',
            	index:'provincia',
            	width:'150',
            	align:'center',
            	editrules:{required:true,edithidden:true},
            	editoptions: {maxlength: 50},
            	editable:true,
            	hidden:true
            }
            
       	],
       	jsonReader: {
        	root: 'gridModel',
	      	id: 'idCliente',
	      	repeatitems: false,
	      	page:  function(obj) { return obj.page; },
	        total: function(obj) { return obj.total; },
	        records: function(obj) { return obj.records; }
     	},
     	height: "auto",
        width: 980,
	   	rowNum:10,
	   	rowList:[10,20,30],
	   	pager: '#dataTablePager',
	   	sortname: 'idCliente',
	    viewrecords: true,
	    shrinkToFit: true,
	    sortorder: "desc",
	    editurl: '../cliente/administrar',
	    caption:"Clientes"
		});
		
		jQuery("#dataTable").jqGrid('navGrid','#dataTablePager',
			{edit:true,add:true,del:true,search:false,refresh:false,view: true},
			{reloadAfterSubmit:true, closeAfterEdit: true, afterSubmit: mensaje, errorTextFormat: mensajeError,onclickSubmit: function (params, postdata){
				return calcularPos(postdata);
				}}, //  default settings for edit
			{closeAfterAdd:true, afterSubmit: mensaje, errorTextFormat: mensajeError,onclickSubmit: function (params, postdata){
				return calcularPos(postdata);
				}}, //  default settings for add
			{width:300,afterSubmit: mensaje},  // delete instead that del:false we need this
			{}, // search options
			{} /* view parameters*/
        	);
        	
        // MENSAJES
		$(".message").click(function () {
	 		$(this).fadeOut();
	 	});
	
	});
	
	</script>
	<?php
	require 'web/pages/commons/header.php';
	?>
			<!-- <div id="right">
	    		<decorator:body />
	    	</div> -->
	    	<div class="message red" id="msjERRORCliente" style="width: 900px;display:none; margin-left: 45px;margin-top: 10px;height: 40px;">
   				<span></span>
   		 	</div>
   		 	<div class="message green" id="msjINFOCliente" style="width: 900px;display:none; margin-left: 45px;margin-top: 10px;">
   				<span></span>
   		 	</div>
			<div id="dataInfo" style="width: 990px; margin-top: 10px;margin-left: 25px;">
				<table id="dataTable" ></table>
				<div id="dataTablePager"></div>
			</div>
		</div>
    	<!--end container-->
    </div>	
	<!--fin wrapper-->
	
</body>
</html>